<?php
/*
Plugin Name: WordPress Reports
Plugin URI: http://tantannoodles.com/toolkit/wordpress-reports/
Description: Generates reports from Google Analytics and Feedburner data
Version: 0.7
Author: Joe Tan
Author URI: http://tantannoodles.com/


Copyright (C) 2006  Joe Tan

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA

Changlog:
0.53 - Fixed divide by 0 bug
0.6  - Added support for multiple site profiles, thx rob!

*/

class TanTanReportsPlugin {
    function install_tracking() {
    global $userdata, $table_prefix;
        $dontTrack = false;
        if (get_option('tantan_gaDontTrackAdmins')) {
            $caps = get_usermeta( $userdata->ID, $table_prefix . 'capabilities');
            if (isset($caps['administrator']) && $caps['administrator']) {
                $dontTrack = true;
            }
        }
        if (!$dontTrack) {
            print get_option('tantan_gaTrackingCode');
            if (get_option('tantan_gaInstallTrackingOutbound')) {
                $this->install_tracking_outbound();
            } 
        }
    
    
    }
    
    function install_tracking_outbound() {
    ?>
    <script type="text/javascript">
    //<![CDATA[ 
    if (document.getElementsByTagName) {
        var ahrefs = document.getElementsByTagName('a');
        for (var i=0; i<ahrefs.length;i++) {
            if (ahrefs[i].href.indexOf('<?bloginfo('url')?>') == -1 && !ahrefs[i].onclick) {
                ahrefs[i].onclick = function () { var track = this.href + ''; urchinTracker ('/outgoing/'+track.substring(7)); }
            }
        }
    }
    //]]>
    </script>
    <?php
    }
    
    function _module($m, $r, $s=0) {
        return array('module' => $m, 'report' => $r, 'sort' => $s);
    }
    function show_reports() {
        $session        = get_option('tantan_gaSession');
        $sessionTimeout = get_option('tantan_gaSessionTimeout');
        $siteProfile    = get_option('tantan_gaSiteProfile');
        $fbURI          = get_option('tantan_fbURI');
        $gaShowReports  = get_option('tantan_gaShowReports');
        
        if (!$gaShowReports['saved']) { // havnt saved preference yet
            $showAllReports = true;
        }
        if (!$siteProfile) { // don't show GA reports if there is no registered profile
            $showAllReports = false;
        }
        if (!$siteProfile && !$fbURI) {
            $html = '<div class="wrap"><h2>Reports</h2>'.
                '<p>Reporting has not yet been configured for this site. </p>'.
                '<a href="admin.php?page=tantan/tantan_reports_config.php">Enter Setup &gt;</a>'.
                '</div>';
            print $html;
            return;
        } else {
            if ($siteProfile) { // found analytics account
                $modules[] = $this->_module('analytics', '7dayreport');
                
                if ($gaShowReports['visits'])       $modules[] = $this->_module('analytics', 'visits');
                if ($gaShowReports['pageviews'])    $modules[] = $this->_module('analytics', 'pageviews');
                if ($gaShowReports['avgpageviews']) $modules[] = $this->_module('analytics', 'avgpageviews');
                if ($gaShowReports['inbound'])      $modules[] = $this->_module('analytics', 'inbound');
                if (get_option('tantan_gaInstallTracking') && get_option('tantan_gaInstallTrackingOutbound'))
                    if ($gaShowReports['outbound'])     $modules[] = $this->_module('analytics', 'outbound');
                if ($gaShowReports['popular'])      $modules[] = $this->_module('analytics', 'popular');
                if ($gaShowReports['entry'])        $modules[] = $this->_module('analytics', 'entry');
                if ($gaShowReports['newreturn'])    $modules[] = $this->_module('analytics', 'newreturn');
                
            }
            if ($fbURI) { // load feed burner reports
                if (is_array($fbURI)) {
                    foreach ($fbURI as $uri) {
                        $modules[] = $this->_module('feedburner', $uri);
                    }
                } else {
                    $modules[] = $this->_module('feedburner', $fbURI);
                }
            }
            include(dirname(__FILE__).'/tantan_reports.html');
        }

        
        /*
        require_once(dirname(__FILE__).'/lib.googleanalytics.php');
        $ga = new tantan_GoogleAnalytics();
        $ga->setSession($session);
        
    
        if ((!$siteProfile || !$ga->isLoggedIn()) && !$fbURI) {
            $html = '<div class="wrap"><h2>Reports</h2>'.
                '<p>Reporting has not yet been configured for this site. </p>'.
                '<a href="admin.php?page=tantan/tantan_reports_config.php">Enter Setup &gt;</a>'.
                '</div>';
            print $html;
            return;
        }    
        $cacheTimeout = get_option('tantan_gaCacheTimeout');
        if ($cacheTimeout && (time() - $cacheTimeout < 3600)) {
            $data = get_option('tantan_gaCacheData');
            $executive = $data['executive'];
            $outbound = $data['outbound'];
            $visitspageviews = $data['visitspageviews'];
            $visitspageviewsCompare = $data['visitspageviewsCompare'];
            $feedburner = $data['feedburner'];
            $topcontent = $data['topcontent'];
            $inbound = $data['inbound'];
            $entrance = $data['entrance'];
        } else {
            $start2 = date('Ymd', time() - 604800);
            //$start = date('Ymd', time() - 518400);
            $start = date('Ymd', time() - 604800);
            $stop = date('Ymd', time() - 86400);
            $modules = array();
            $data = array();
            if ($siteProfile) {
                // should cache these requests
                $executive = $ga->getReport($siteProfile, $start, $stop, 'executive');
                $visitspageviews = $ga->getReport($siteProfile, $start, $stop, 'visitspageviews');
                $visitspageviewsCompare = $ga->getReport($siteProfile, $start, $stop, 'visitspageviewscompare');
    
                // $referals = $ga->getReport($siteProfile, $start, $stop, 'referals');
                if (get_option('tantan_gaInstallTracking') && get_option('tantan_gaInstallTrackingOutbound')) {
                    $outbound = $ga->getReport($siteProfile, $start, $stop, 'outbound');
                }
                $inbound = $ga->getReport($siteProfile, $start, $stop, 'referals');
                $topcontent = $ga->getReport($siteProfile, $start, $stop, 'content');
                $entrance = $ga->getReport($siteProfile, $start, $stop, 'entrance');
        
                $data['executive'] = $executive;
                $data['outbound'] = $outbound;
                $data['visitspageviews'] = $visitspageviews;
                $data['visitspageviewsCompare'] = $visitspageviewsCompare;
                $data['topcontent'] = $topcontent;
                $data['inbound'] = $inbound;
                $data['entrance'] = $entrance;
            }
            if ($fbURI) {
                if (is_array($fbURI)) {
                    
                    //foreach ($fbURI as $uri) {
                    //    $feedburner[] = $fb->getFeedData($uri, $start2, $stop);
                    //}
                    //$data['feedburner'] = $feedburner;
                    
                    foreach ($fbURI as $uri) {
                        $modules['feedburner'][] = $uri;
                    }
                    
                } else {
                    $modules['feedburner'][] = $fbURI;
                    
                    //$feedburner = array($fb->getFeedData($fbURI, $start2, $stop));
                    //$data['feedburner'] = $feedburner;
                    
                }
                
            }
    
            update_option('tantan_gaCacheData', $data);
            update_option('tantan_gaCacheTimeout', time());
            
        }
        $visitsNow = 0;
        $visitsPast = 0;
        if ($siteProfile) {
            if (is_array($visitspageviewsCompare['Visits']['records'])) foreach ($visitspageviewsCompare['Visits']['records'] as $visit) {
                $visitsNow += $visit['Visits'];
                $visitsPast += $visit['Visits (2)'];
            }
            if ($visitsPast > 0) {
                $visitsPercent = round(($visitsNow / $visitsPast),2);
            } else {
                $visitsPercent = 1;
            }
            if ($visitsPercent >= 1) {
                $visitsPercentLabel = '<span class="plus">(+'.(($visitsPercent * 100)-100).'%)</span> ';
            } else {
                $visitsPercentLabel = '<span class="minus">('.(($visitsPercent * 100)-100).'%)</span> ';
            }
            
            
            $viewsNow = 0;
            $viewsPast = 0;
            if (is_array($visitspageviewsCompare['Pageviews']['records'])) foreach ($visitspageviewsCompare['Pageviews']['records'] as $view) {
                $viewsNow += $view['Pageviews'];
                $viewsPast += $view['Pageviews (2)'];
            }
            if ($viewsPast > 0) {
                $viewsPercent = round($viewsNow / $viewsPast, 2);
            } else {
                $viewsPercent = 1;
            }
            if ($viewsPercent >= 1) {
                $viewsPercentLabel = '<span class="plus">(+'.(($viewsPercent * 100)-100).'%)</span> ';
            } else {
                $viewsPercentLabel = '<span class="minus">('.(($viewsPercent * 100)-100).'%)</span> ';
            }
        }
        
        include(dirname(__FILE__).'/tantan_reports.html');
        */
        
    }
    
    function admin_options() {
        global $userdata, $table_prefix;
        add_menu_page('Reports', 'Reports', 2, __FILE__, array(&$this, 'show_reports'));
        $caps = get_usermeta( $userdata->ID, $table_prefix . 'capabilities');
        if (isset($caps['administrator']) && $caps['administrator']) {
    	   add_submenu_page(__FILE__, 'Setup', 'Setup', 10, 'tantan/tantan_reports_config.php');
        }
    }
    
    function TanTanReportsPlugin() {
        add_action('admin_menu', array(&$this, 'admin_options'));
        if (get_option('tantan_gaInstallTracking')) {
            add_action('wp_footer', array(&$this, 'install_tracking'));
        }
    }
}

$TanTanReportsPlugin =& new TanTanReportsPlugin();

?>